package com.damai.action.json;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.api.ApiConfig;
import com.citywithincity.utils.MapUtil;
import com.damai.action.IParamParser;

class JsonParam implements IParamParser {

	private IGetJson getJson;
	private IParamGetter[] getters;
	
	public JsonParam(IGetJson getJson,IParamGetter[] getters) {
		this.getJson = getJson;
		this.getters = getters;
	}
	
	
	
	@Override
	public Object[] parseParam(HttpServletRequest request) throws IOException {
		Map<String, Object> json = getJson.getJson(request);
		
		if(ApiConfig.out){
			StringBuilder sb = new StringBuilder();
			sb.append(request.getRequestURI()).append(" ip:")
				.append(request.getRemoteAddr())
				.append(" ");
			MapUtil.toString(sb,json);
			ApiConfig.info(sb.toString(), ApiConfig.in);
		}
		
		json.put("request", request);
		
		final IParamGetter[] getters = this.getters;
		final int len = getters.length;
		
		Object[] objects = new Object[len];
		int index=0;
		for (IParamGetter getter : getters) {
			objects[index++]=getter.get(json);
		}
		
		
		if(ApiConfig.debug()){
			//环境
			request.setAttribute("_json", json);
		}
		
		return objects;
	}

	

	
	
}
